using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web.UI.WebControls;
using System.Xml;
using Framework.Library.Base.Base;
using Framework.Library.Base.Extensions;
using Framework.Library.Core.Config;
using Framework.Library.Core.Utils;
using Framework.Library.Data.DAL;
using Framework.Library.Data.DAO;
using Framework.Library.Data.DAL.JObject;

namespace Framework.Portal.Layouts.Admin.Components.Modules
{
    public partial class ModuleControls : BaseControl
    {
        private readonly string MENUNAME = string.Empty;
        private readonly ArrayList lstFile = new ArrayList();

        public ModuleControls()
        {
        }

        public ModuleControls(JSection section)
        {
            MENUNAME = section.title;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                drgModules.DataSource = StaticData.ControlType;
                drgModules.DataBind();
                LoadData(0);
                lblCommandName.Text = MENUNAME;
                MiscUtility.FillIndex(dropControlOrder, 30, 1);
            }
        }

        protected void tvwControls_SelectedNodeChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tvwControls.SelectedNode.Value))
            {
                txtID.Text = tvwControls.SelectedNode.Value;
                lblUpdateStatus.Text = string.Empty;
                LoadData();
            }
        }

        protected void btnCreate_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtControlName.Text) && (dropPath.SelectedIndex > 0))
            {
                var moduleControl = new PortalControl();
                moduleControl.PORTALID = Session.WorkingPortal().PORTALID;
                moduleControl.CONTROLNAME = txtControlName.Text.Trim();
                moduleControl.CONTROLDESCRIPTION = txtControlDescription.Text.Trim();
                moduleControl.CONTROLPATH = dropPath.SelectedValue;
                moduleControl.CONTROLORDER = ConvertUtility.ToInt32(dropControlOrder.SelectedValue);
                if (dropEditPath.SelectedIndex == -1)
                    moduleControl.CONTROLEDITPATH = null;
                else
                    moduleControl.CONTROLEDITPATH = dropEditPath.SelectedValue;
                if (dropXmlPath.SelectedIndex == -1)
                    moduleControl.COLUMNXMLPATH = null;
                else
                    moduleControl.COLUMNXMLPATH = dropXmlPath.SelectedValue;
                moduleControl.SA = Convert.ToInt32(chkPermission.Checked);
                moduleControl.CONTROLTYPE = Convert.ToInt32(drgModules.SelectedValue);
                ManagerFactory.DAOEntity.Insert(moduleControl);
                lblUpdateStatus.Text = Localization.GetText("MESSAGE", "MSG_UPDATE_SUCCESS");
                LoadData(Convert.ToInt32(drgModules.SelectedValue));
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(txtControlName.Text) && (dropPath.SelectedIndex > 0))
            {
                var moduleControl = new PortalControl();
                moduleControl.CONTROLID = Convert.ToInt32(txtID.Text);
                moduleControl.PORTALID = Session.WorkingPortal().PORTALID;
                moduleControl.CONTROLNAME = txtControlName.Text.Trim();
                moduleControl.CONTROLDESCRIPTION = txtControlDescription.Text.Trim();
                moduleControl.CONTROLPATH = dropPath.SelectedValue;
                moduleControl.CONTROLORDER = ConvertUtility.ToInt32(dropControlOrder.SelectedValue);
                if (dropEditPath.SelectedIndex == -1)
                    moduleControl.CONTROLEDITPATH = null;
                else
                    moduleControl.CONTROLEDITPATH = dropEditPath.SelectedValue;
                if (dropXmlPath.SelectedIndex == -1)
                    moduleControl.COLUMNXMLPATH = null;
                else
                    moduleControl.COLUMNXMLPATH = dropXmlPath.SelectedValue;
                moduleControl.SA = Convert.ToInt32(chkPermission.Checked);
                moduleControl.CONTROLTYPE = Convert.ToInt32(drgModules.SelectedValue);
                ManagerFactory.DAOEntity.Update(moduleControl);
                lblUpdateStatus.Text = Localization.GetText("MESSAGE", "MSG_UPDATE_SUCCESS");
                LoadData(Convert.ToInt32(drgModules.SelectedValue));
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(txtID.Text))
            {
                ManagerFactory.DAOEntity.Delete(new PortalControl
                                                                     {CONTROLID = Convert.ToInt32(txtID.Text)});
                lblUpdateStatus.Text = Localization.GetText("MESSAGE", "MSG_UPDATE_SUCCESS");
                LoadData(Convert.ToInt32(drgModules.SelectedValue));
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            txtControlDescription.Text = string.Empty;
            txtControlName.Text = string.Empty;
            dropPath.SelectedIndex = -1;
            dropXmlPath.SelectedIndex = -1;
            dropEditPath.SelectedIndex = -1;
            dropControlOrder.SelectedIndex = -1;
        }

        protected void drgModules_SelectedIndexChanged(object sender, EventArgs e)
        {
            int moduleID = Convert.ToInt32(drgModules.SelectedValue);
            LoadData(moduleID);
        }

        private void GetPath(string path, string ext)
        {
            lstFile.Add("-----------------------------------");
            string filename = Server.MapPath(String.Format("{0}Layouts/Layouts.xml", Configurations.ROOTDIR));
            if (File.Exists(filename))
            {
                var _doc = new XmlDocument();
                _doc.Load(filename);
                XmlNode xmlPageNode = _doc.SelectSingleNode(string.Format("//site[@id='{0}']", Session.WorkingPortal().PORTALID));
                if (xmlPageNode != null)
                {
                    string dirPath =
                        Server.MapPath(String.Format("{0}Layouts/{1}/{2}", Configurations.ROOTDIR, xmlPageNode.InnerText,
                                                     path));
                    GetFiles(Configurations.ROOTDIR, dirPath, ext);
                }
            }
        }

        private void GetFiles(string rootPath, string dirPath, string ext)
        {
            if (Directory.Exists(dirPath))
            {
                string[] files = Directory.GetFiles(dirPath);
                for (int i = 0; i < files.Length; i++)
                {
                    if (files[i].EndsWith("." + ext))
                    {
                        string temp = files[i].Replace(Server.MapPath(rootPath), string.Empty);
                        temp = temp.Replace("\\", "/");
                        if (!temp.StartsWith("/")) temp = "/" + temp;
                        lstFile.Add(temp);
                    }
                }
                string[] folders = Directory.GetDirectories(dirPath);
                for (int i = 0; i < folders.Length; i++)
                {
                    GetFiles(rootPath, folders[i], ext);
                }
            }
            lstFile.Sort();
        }

        private void LoadData()
        {
            if (txtID.Text != string.Empty)
            {
                PortalControl curControl =
                    ManagerFactory.DAOEntity.GetInfo(new PortalControl() { CONTROLID = ConvertUtility.ToInt32(txtID.Text) });
                if (curControl != null)
                {
                    if (curControl == null) return;
                    txtControlName.Text = curControl.CONTROLNAME;
                    MiscUtility.SelectItemFromList(dropPath, curControl.CONTROLPATH);
                    txtControlDescription.Text = curControl.CONTROLDESCRIPTION;
                    MiscUtility.SelectItemFromList(dropControlOrder, curControl.CONTROLORDER.ToString());
                }
            }
        }

        private void LoadData(int ModuleID)
        {
            switch (ModuleID)
            {
                case 0:
                    GetPath("Modules", "ascx");
                    break;
                case 1:
                    GetPath("Components", "ascx");
                    break;
                case 2:
                    GetPath("Popups", "ascx");
                    break;
                default:
                    break;
            }
            dropPath.Items.Clear();
            dropPath.DataSource = lstFile;
            dropPath.DataBind();
            dropXmlPath.Items.Clear();
            dropXmlPath.DataSource = lstFile;
            dropXmlPath.DataBind();
            dropEditPath.Items.Clear();
            dropEditPath.DataSource = lstFile;
            dropEditPath.DataBind();

            txtControlDescription.Text = string.Empty;
            txtControlName.Text = string.Empty;
            dropPath.SelectedIndex = -1;
            dropXmlPath.SelectedIndex = -1;
            dropEditPath.SelectedIndex = -1;
            dropControlOrder.SelectedIndex = -1;

            tvwControls.Nodes.Clear();
            List<PortalControl> dtControls = ManagerFactory.DAOEntity.GetList(new PortalControl() { CONTROLTYPE = ModuleID, PORTALID = Session.WorkingPortal().PORTALID });
            if (dtControls != null)
            {
                List<string> lstDir = new List<string>();
                foreach (PortalControl rows in dtControls)
                {
                    if (!string.IsNullOrEmpty(rows.CONTROLPATH))
                    {
                        string[] arrDir = rows.CONTROLPATH.Split('/');
                        string dir = arrDir[1] + "/" + arrDir[2] + "/" + arrDir[3] + "/" + arrDir[4];
                        bool isExists = lstDir.Contains(dir);
                        if (!isExists)
                            lstDir.Add(dir);
                    }
                }
                lstDir.Sort();
                foreach (var s in lstDir)
                {
                    string dir = s.Split('/')[3];
                    var rootNode = new TreeNode();
                    rootNode.Text = dir;
                    rootNode.Value = string.Empty;
                    rootNode.Expanded = true;
                    List<PortalControl> lstControl = dtControls.FindAll(x => (x.CONTROLPATH.IndexOf(s) > 0));
                    if (lstControl != null)
                    {
                        foreach (PortalControl rows in lstControl)
                        {
                            var childNode = new TreeNode();
                            childNode.Text = rows.CONTROLNAME;
                            childNode.Value = rows.CONTROLID.ToString();
                            rootNode.ChildNodes.Add(childNode);
                        }                       
                    }
                    tvwControls.Nodes.Add(rootNode);
                }
            }
        }
    }
}